package com.jh.jingfei.main.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jh.jingfei.R;
import com.jh.jingfei.models.RobotGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lxb
 * Created by lion on 2017/12/2.
 */

public class CrewRvAdapter extends RecyclerView.Adapter<CrewRvAdapter.CrewVH> {

    private List<RobotGroup> robotGroups;

    private Context mContext;

    public CrewRvAdapter(Context mContext) {
        this.mContext = mContext;
        robotGroups = new ArrayList<>();
    }

    @Override
    public CrewVH onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater lf = LayoutInflater.from(mContext);
        View v = lf.inflate(R.layout.crew_item, parent, false);
        return new CrewVH(v);
    }

    @Override
    public void onBindViewHolder(CrewVH holder, int position) {
        RobotGroup rg = getItem(position);
        holder.robot_group_name.setText(rg.getName());
    }

    @Override
    public int getItemCount() {
        return robotGroups.size();
    }

    public void addItems(List<RobotGroup> robotGroups) {
        int len = this.robotGroups.size();
        this.robotGroups.addAll(robotGroups);
        notifyItemRangeInserted(len, robotGroups.size());
    }

    public void updateItems(List<RobotGroup> robotGroups) {
        this.robotGroups.clear();
        this.robotGroups.addAll(robotGroups);
        notifyDataSetChanged();
    }

    public RobotGroup getItem(int position) {
        if (position < 0 || position >= this.robotGroups.size()) {
            return null;
        }
        return robotGroups.get(position);
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public class CrewVH extends RecyclerView.ViewHolder {
        TextView robot_group_name;

        public CrewVH(View itemView) {
            super(itemView);
            robot_group_name = itemView.findViewById(R.id.robot_group_txt);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemClick(getAdapterPosition());
                    }
                }
            });
        }
    }
}
